package com.demo.config;

import com.demo.function.spring.loadbalancer.GrayLoadBalancer;
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.cloud.loadbalancer.core.ReactorServiceInstanceLoadBalancer;
import org.springframework.cloud.loadbalancer.core.ServiceInstanceListSupplier;
import org.springframework.cloud.loadbalancer.support.LoadBalancerClientFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.core.env.Environment;

/**
 * 灰度负载均衡配置
 * 这里不能使用@Configuration，这样会使该配置成为全局配置，导致serviceID为NULL，因为本身就是靠environment区分contextName来设置serviceID。
 * 必须使用@LoadBalancerClient指定服务使用灰度负载均衡器或者使用@LoadBalancerClients定义全局配置
 * @author K
 */
public class GrayLoadBalancerConfig {

    @Bean
    public ReactorServiceInstanceLoadBalancer grayLoadBalancer(Environment environment, LoadBalancerClientFactory loadBalancerClientFactory) {
        String name = environment.getProperty(LoadBalancerClientFactory.PROPERTY_NAME);
        ObjectProvider<ServiceInstanceListSupplier> provider = loadBalancerClientFactory.getLazyProvider(name,
                ServiceInstanceListSupplier.class);
        return new GrayLoadBalancer(provider);
    }
}
